<script setup>
import {
  getEmployeeListApi,
  disableUserApi,
  getUserDetailsApi,
  assignRoleApi
} from '@/api/user'
import { getRolesEnableApi } from '@/api/role'
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'

// 员工列表
const employeeList = ref([])
// 查询员工的参数列表
const queryParams = ref({
  keyWord: '' // 模糊搜索关键字
})
const setEmployeeList = async () => {
  const res = await getEmployeeListApi(queryParams.value)
  employeeList.value = res.data.records
}

// 角色对话框
const showRoleDialog = ref(false)
// 员工的角色列表
const roles = ref([])
// 员工角色id列表
const roleId = ref('')
// 选中的员工id
const selectedId = ref('')
// 弹出分配权限对话框
const assignRole = async (id) => {
  // 开启加载效果
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    selectedId.value = id
    // 获取可分配的角色列表
    const res1 = await getRolesEnableApi()
    roles.value = res1.data
    // 回显员工原本拥有的角色
    const res2 = await getUserDetailsApi(id)
    console.log(res2.data)
    roleId.value = res2.data
    // 关闭加载效果，弹出层
    showRoleDialog.value = true
  } finally {
    // 防止出现异常一直在加载
    loading.close()
  }
}
// 分配角色确定按钮
const assignRoleComfirm = async () => {
  await assignRoleApi({ id: selectedId.value, roleId: roleId.value })
  ElMessage.success('分配角色成功')
  showRoleDialog.value = false
}

// 搜索输入框值改变时
const timer = ref('')
const onNameChange = () => {
  clearTimeout(timer.value)
  timer.value = setTimeout(() => {
    setEmployeeList()
  }, 1000) // 延时一秒
}

// 禁用用户
const disableUser = async (id, status) => {
  ElMessageBox.confirm('确认禁用此用户吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await disableUserApi(id, status)
    ElMessage.success('操作成功')
    setEmployeeList()
  })
}

onMounted(() => setEmployeeList())
</script>

<template>
  <div class="container">
    <div
      style="display: flex; justify-content: space-between; margin-bottom: 20px"
    >
      <el-input
        style="width: 230px"
        v-model="queryParams.keyWord"
        :prefix-icon="Search"
        placeholder="输入员工姓名全员搜索"
        @input="onNameChange"
      />
      <el-row class="opeate-tools" type="flex" justify="end">
        <el-button type="primary" @click="$router.push('/user/details')"
          >添加员工</el-button
        >
      </el-row>
    </div>
    <!-- 表格组件 -->
    <el-table :data="employeeList">
      <el-table-column label="头像" width="100px">
        <template #default="{ row }">
          <el-avatar v-if="row.avatar" :src="row.avatar" />
          <span v-else class="username"> {{ row.nickname.charAt(0) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="nickname" />
      <el-table-column label="手机号" prop="phone" />
      <el-table-column label="类型" prop="type">
        <template #default="{ row }">
          <el-text v-if="row.type === 1" type="info">个人用户</el-text>
          <el-text v-if="row.type === 2" type="info">车商用户</el-text>
          <el-text v-if="row.type === 3" type="info">审核员</el-text>
          <el-text v-if="row.type === 4" type="info">系统管理员</el-text>
        </template>
      </el-table-column>
      <el-table-column label="帐号状态" prop="status">
        <template #default="{ row }">
          <el-text :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '可用' : '禁用' }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center">
        <template #default="{ row }">
          <el-row>
            <el-col :span="8"
              ><el-link
                type="primary"
                @click.prevent="$router.push(`/user/details/${row.id}`)"
                >编辑</el-link
              ></el-col
            >
            <el-col :span="8"
              ><el-link type="primary" @click.prevent="assignRole(row.id)"
                >角色</el-link
              ></el-col
            >
            <el-col :span="8">
              <el-link
                v-if="row.status === 1"
                type="warning"
                @click.prevent="disableUser(row.id, 0)"
                >禁用
              </el-link>
              <el-link
                v-else
                type="success"
                @click.prevent="disableUser(row.id, 1)"
                >启用
              </el-link>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 角色对话框 -->
    <el-dialog title="角色" v-model="showRoleDialog">
      <el-radio-group v-model="roleId">
        <el-radio v-for="item in roles" :key="item.id" :label="item.id">
          {{ item.roleName }}
        </el-radio>
      </el-radio-group>
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="small" @click="assignRoleComfirm"
            >确定</el-button
          >
          <el-button size="small" @click="showRoleDialog = false"
            >取消</el-button
          >
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.container {
  background-color: #fff;
  padding: 20px;
  min-height: 650px;
}
.username {
  height: 30px;
  width: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  color: #fff;
  background: #04c9be;
  font-size: 12px;
  display: inline-block;
}
</style>
